from typing import Dict, Any, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from core.pagination import paging_data, _CustomPageParams
from fastapi import HTTPException, status

from modules.project.models.project_model import Project
from modules.project.schemas.project_schema import ProjectCreate, ProjectUpdate
from modules.project.params.project_params import ProjectQuery
from modules.project.curd.project_curd import project_dao
from utils.query_builder import build_select_stmt


class ProjectService:
    @staticmethod
    async def get_list_with_pagination(db: AsyncSession, query_params: ProjectQuery) -> Dict[str, Any]:
        stmt = build_select_stmt(
            Project,
            query_params,
            order_by_desc="id",
            text_like_fields=None,
        )
        params = _CustomPageParams(page=query_params.page, size=query_params.size)
        return await paging_data(db, stmt, params=params)

    @staticmethod
    async def get_by_id(db: AsyncSession, pk: Any) -> Optional[Project]:
        repo = await project_dao.get_by_id(db, pk)
        return repo

    @staticmethod
    async def create(db: AsyncSession, data: ProjectCreate) -> Project:
        repo = await project_dao.create(db, data)
        await db.commit()
        await db.refresh(repo)
        return repo

    @staticmethod
    async def update(db: AsyncSession, pk: Any, data: ProjectUpdate) -> Optional[Project]:
        repo = await project_dao.update(db, pk, data)
        if not repo:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"记录 {pk} 不存在")
        await db.commit()
        await db.refresh(repo)
        return repo

    @staticmethod
    async def delete(db: AsyncSession, pk: Any) -> bool:
        repo = await project_dao.delete(db, pk)
        if not repo:
            return False
        await db.commit()
        return True